<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Library Management System - Staff</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
    <style>
        .sidebar {
            height: 100vh;
            background-color: #2c3e50;
            color: white;
            padding-top: 20px;
        }
        .sidebar a {
            color: white;
            text-decoration: none;
            display: block;
            padding: 10px 20px;
            margin-bottom: 5px;
        }
        .sidebar a:hover {
            background-color: #34495e;
        }
        .sidebar a.active {
            background-color: #1abc9c;
        }
        .content {
            padding: 20px;
            overflow-y: auto;
            height: 100vh;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #e9ecef;
        }
        .search-bar {
            margin-bottom: 20px;
        }
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }
        .modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 5px;
            width: 100%;
            max-width: 600px;
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        .logout-btn {
            cursor: pointer;
        }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <!-- Sidebar -->
        <div class="col-md-2 sidebar">
            <h3 class="text-center mb-4">Library System</h3>
            <a href="/books.html"><i class="bi bi-book"></i> Books</a>
            <a href="/staff.html" class="active"><i class="bi bi-people"></i> Staff</a>
            <a href="/users.html"><i class="bi bi-person"></i> Users</a>
            <div class="mt-5">
                <a href="#" id="logoutLink" class="logout-btn"><i class="bi bi-box-arrow-right"></i> Logout</a>
            </div>
        </div>

        <!-- Main Content -->
        <div class="col-md-10 content">
            <div class="header">
                <h2>Staff Management</h2>
                <div id="userInfo"></div>
            </div>

            <!-- Search Bar -->
            <div class="search-bar">
                <div class="row g-3">
                    <div class="col-md-3">
                        <input type="text" class="form-control" id="searchName" placeholder="Name">
                    </div>
                    <div class="col-md-3">
                        <input type="text" class="form-control" id="searchEmployeeId" placeholder="Employee ID">
                    </div>
                    <div class="col-md-3">
                        <input type="text" class="form-control" id="searchPosition" placeholder="Position">
                    </div>
                    <div class="col-md-3">
                        <button class="btn btn-primary" id="searchBtn">Search</button>
                        <button class="btn btn-secondary" id="resetBtn">Reset</button>
                        <button class="btn btn-success" id="addStaffBtn">Add Staff</button>
                    </div>
                </div>
            </div>

            <!-- Staff Table -->
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Employee ID</th>
                        <th>Position</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Hire Date</th>
                        <th>Actions</th>
                    </tr>
                    </thead>
                    <tbody id="staffTableBody">
                    <!-- Staff will be loaded here -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Add/Edit Staff Modal -->
<div class="modal" id="staffModal">
    <div class="modal-content">
        <div class="modal-header">
            <h4 id="modalTitle">Add New Staff</h4>
            <button type="button" class="btn-close" id="closeModal"></button>
        </div>
        <form id="staffForm">
            <input type="hidden" id="staffId">
            <div class="mb-3">
                <label for="name" class="form-label">Name</label>
                <input type="text" class="form-control" id="name" required>
            </div>
            <div class="mb-3">
                <label for="employeeId" class="form-label">Employee ID</label>
                <input type="text" class="form-control" id="employeeId" required>
            </div>
            <div class="mb-3">
                <label for="position" class="form-label">Position</label>
                <input type="text" class="form-control" id="position">
            </div>
            <div class="mb-3">
                <label for="email" class="form-label">Email</label>
                <input type="email" class="form-control" id="email">
            </div>
            <div class="mb-3">
                <label for="phone" class="form-label">Phone</label>
                <input type="text" class="form-control" id="phone">
            </div>
            <div class="mb-3">
                <label for="hireDate" class="form-label">Hire Date</label>
                <input type="date" class="form-control" id="hireDate">
            </div>
            <button type="submit" class="btn btn-primary">Save</button>
        </form>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Check if user is logged in
    const token = localStorage.getItem('token');
    if (!token) {
        window.location.href = '/login.html';
    }

    // Load user info
    const user = JSON.parse(localStorage.getItem('user'));
    if (user) {
        document.getElementById('userInfo').textContent = `Welcome, ${user.username}`;
    }

    // Logout functionality
    document.getElementById('logoutLink').addEventListener('click', function(e) {
        e.preventDefault();
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        window.location.href = '/login.html';
    });

    // Load all staff on page load
    loadStaff();

    // Load staff from API
    async function loadStaff(criteria = {}) {
        try {
            let url = '/api/staff';
            if (Object.keys(criteria).length > 0) {
                const params = new URLSearchParams();
                Object.entries(criteria).forEach(([key, value]) => {
                    if (value) params.append(key, value);
                });
                url += `?${params.toString()}`;
            }

            const response = await fetch(url, {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });

            if (!response.ok) {
                if (response.status === 401) {
                    // Token expired or invalid, redirect to login
                    localStorage.removeItem('token');
                    window.location.href = '/login.html';
                }
                throw new Error('Failed to load staff');
            }

            const staffList = await response.json();
            renderStaffTable(staffList);
        } catch (error) {
            console.error('Error loading staff:', error);
            alert('Failed to load staff. Please try again.');
        }
    }

    // Render staff table
    function renderStaffTable(staffList) {
        const tableBody = document.getElementById('staffTableBody');
        tableBody.innerHTML = '';

        staffList.forEach(staff => {
            const row = document.createElement('tr');
            // Format hire date for display
            const hireDate = staff.hireDate ? new Date(staff.hireDate).toISOString().split('T')[0] : '';

            row.innerHTML = `
                <td>${staff.id}</td>
                <td>${staff.name}</td>
                <td>${staff.employeeId}</td>
                <td>${staff.position || '-'}</td>
                <td>${staff.email || '-'}</td>
                <td>${staff.phone || '-'}</td>
                <td>${hireDate}</td>
                <td>
                    <button class="btn btn-sm btn-primary edit-btn" data-id="${staff.id}">Edit</button>
                    <button class="btn btn-sm btn-danger delete-btn" data-id="${staff.id}">Delete</button>
                </td>
            `;
            tableBody.appendChild(row);
        });

        // Add event listeners to edit and delete buttons
        document.querySelectorAll('.edit-btn').forEach(btn => {
            btn.addEventListener('click', () => editStaff(btn.getAttribute('data-id')));
        });

        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', () => deleteStaff(btn.getAttribute('data-id')));
        });
    }

    // Search functionality
    document.getElementById('searchBtn').addEventListener('click', () => {
        const criteria = {
            name: document.getElementById('searchName').value,
            employeeId: document.getElementById('searchEmployeeId').value,
            position: document.getElementById('searchPosition').value
        };
        loadStaff(criteria);
    });

    // Reset search
    document.getElementById('resetBtn').addEventListener('click', () => {
        document.getElementById('searchName').value = '';
        document.getElementById('searchEmployeeId').value = '';
        document.getElementById('searchPosition').value = '';
        loadStaff();
    });

    // Add staff button
    document.getElementById('addStaffBtn').addEventListener('click', () => {
        document.getElementById('modalTitle').textContent = 'Add New Staff';
        document.getElementById('staffForm').reset();
        document.getElementById('staffId').value = '';
        document.getElementById('staffModal').style.display = 'flex';
    });

    // Close modal
    document.getElementById('closeModal').addEventListener('click', () => {
        document.getElementById('staffModal').style.display = 'none';
    });

    // Close modal when clicking outside
    window.addEventListener('click', (e) => {
        if (e.target === document.getElementById('staffModal')) {
            document.getElementById('staffModal').style.display = 'none';
        }
    });

    // Edit staff
    async function editStaff(id) {
        try {
            const response = await fetch(`/api/staff/${id}`, {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });

            if (!response.ok) {
                throw new Error('Failed to load staff details');
            }

            const staff = await response.json();
            document.getElementById('modalTitle').textContent = 'Edit Staff';
            document.getElementById('staffId').value = staff.id;
            document.getElementById('name').value = staff.name;
            document.getElementById('employeeId').value = staff.employeeId;
            document.getElementById('position').value = staff.position || '';
            document.getElementById('email').value = staff.email || '';
            document.getElementById('phone').value = staff.phone || '';

            // Format date for input field
            if (staff.hireDate) {
                document.getElementById('hireDate').value = new Date(staff.hireDate).toISOString().split('T')[0];
            } else {
                document.getElementById('hireDate').value = '';
            }

            document.getElementById('staffModal').style.display = 'flex';
        } catch (error) {
            console.error('Error loading staff details:', error);
            alert('Failed to load staff details. Please try again.');
        }
    }

    // Delete staff
    async function deleteStaff(id) {
        if (confirm('Are you sure you want to delete this staff member?')) {
            try {
                const response = await fetch(`/api/staff/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (!response.ok) {
                    throw new Error('Failed to delete staff');
                }

                // Reload staff list
                loadStaff();
            } catch (error) {
                console.error('Error deleting staff:', error);
                alert('Failed to delete staff. Please try again.');
            }
        }
    }

    // Staff form submission
    document.getElementById('staffForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        const staffId = document.getElementById('staffId').value;
        const staffData = {
            name: document.getElementById('name').value,
            employeeId: document.getElementById('employeeId').value,
            position: document.getElementById('position').value,
            email: document.getElementById('email').value,
            phone: document.getElementById('phone').value,
            hireDate: document.getElementById('hireDate').value
        };

        try {
            let url = '/api/staff';
            let method = 'POST';

            if (staffId) {
                url = `/api/staff/${staffId}`;
                method = 'PUT';
            }

            const response = await fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(staffData)
            });

            if (!response.ok) {
                const errorMsg = await response.text();
                throw new Error(errorMsg || (staffId ? 'Failed to update staff' : 'Failed to add staff'));
            }

            // Close modal and reload staff list
            document.getElementById('staffModal').style.display = 'none';
            loadStaff();
        } catch (error) {
            console.error('Error saving staff:', error);
            alert(error.message || 'Failed to save staff. Please try again.');
        }
    });
</script>
</body>
</html>
